package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import logic.UpdateLogic;
import model.Shain;
import util.Authorizer;
import exception.BusinessException;
import exception.NotLoginedException;
import exception.SystemException;

/**
 * Servlet implementation class UpdatelServlet
 */
@WebServlet("/UpdateServlet")
public class UpdateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//リクエストとレスポンスの文字コードをUTF-8に設定
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		
		//社員情報モデルクラス
		Shain shain;
		//ログインを確認
		try{
			Authorizer a = new Authorizer(request);
			a.isLogined();
		}
		//ログインしていない場合、ログイン画面に遷移させる
		catch (NotLoginedException nle){
			this.getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
			return;
		}

		//パラメータの取得：社員番号
		String shain_no = request.getParameter("shain_no");

		//ロジックを実行する
		try{
			UpdateLogic logic = new UpdateLogic();
			shain = logic.executeUpdate(shain_no);
		}
		//システム例外が発生した場合、システムエラー画面に遷移
		catch (SystemException se){
			this.getServletContext().getRequestDispatcher("/system_error.jsp").forward(request, response);
			return;
		}
		//業務例外が発生した場合、エラーメッセージを表示し、更新画面を表示
		catch (BusinessException be){
			request.setAttribute("errorMessages", be.getErrorMessages());
			this.getServletContext().getRequestDispatcher("/update.jsp").forward(request, response);
			return;
		}

		//処理完了した場合、取得した社員情報をリクエストスコープに登録し、更新画面を表示する
		request.setAttribute("shain_no", shain.shain_no);
		request.setAttribute("shain_no_old", shain.shain_no);
		request.setAttribute("first_name", shain.first_name);
		request.setAttribute("last_name", shain.last_name);
		request.setAttribute("sex", shain.sex);
		request.setAttribute("enter_date", shain.enter_date);
		request.setAttribute("section_code", shain.section_code);
		request.setAttribute("e_mail", shain.e_mail);
		this.getServletContext().getRequestDispatcher("/update.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO　POSTリクエストの異常処理
	}

}
